package com.xbongbong.paas.script.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.crm.help.SearchCustomerHelp;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.script.pojo.dto.ScriptBaseDTO;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.helper.GaodeGeoHelper;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.paas.toolbox.wrap.BaseVO;
import com.xbongbong.paas.toolbox.wrap.XbbResponse;
import com.xbongbong.pro.config.ProBaseConfig;
import com.xbongbong.pro.constant.XbbProConstant;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.saas.domain.entity.ext.CustomerEntityExt;
import com.xbongbong.saas.enums.business.CustomerManagementEnum;
import com.xbongbong.saas.model.CustomerModel;
import com.xbongbong.saas.service.CustomerStageLogService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Lazy;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * Description: 客户相关的修复脚本
 *
 * @author W.Rajer
 * @version v4.80
 * @date 2019/12/12 15:52
 * @since v4.8.0
 */
@RestController
@RequestMapping(XbbProConstant.API_ROOT_PREFIX + "/script/customer")
public class CustomerScriptController {
    private static final Logger LOG = LoggerFactory.getLogger(CustomerScriptController.class);

    @Resource
    private ProBaseConfig proBaseConfig;
    @Lazy
    @Resource
    private SearchCustomerHelp searchCustomerHelp;
    @Resource
    private CustomerModel customerModel;
    @Resource
    private CustomerStageLogService customerStageLogService;

    @RequestMapping(value = "/fixCustomerCoordinates", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String fixCustomerCoordinates(@RequestBody @Valid ScriptBaseDTO scriptBaseDTO, BindingResult br) {
        XbbResponse<BaseVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                if (!Objects.equals(scriptBaseDTO.getXbbCode(), proBaseConfig.getXbbCode())) {
                    LOG.error("fixCustomerCoordinates 密码错误，停止定时任务！");
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100066);
                }
                String oneCorpid = scriptBaseDTO.getOneCorpid();
                if (Objects.isNull(oneCorpid)) {

                } else {
                    Map<String, Object> param = new HashMap<>();
                    param.put("corpid", oneCorpid);
                    param.put("negDel", DelEnum.REMOVE_COMPLETELY.getDel());
                    Integer entitysCount = customerModel.getEntitysCount(param);
                    Integer pageSize = 100;
                    Integer pageNum = entitysCount / pageSize + 1;
                    for (int i = 1; i <= pageNum; i++) {
                        int start = (i - 1) * pageSize;
                        int end = i * pageSize;
                        param.put("start", start);
                        param.put("pageNum", end);
                        LOG.info("start=" + start + ", end=" + end + ", total=" + entitysCount);
                        List<CustomerEntityExt> entitys = customerModel.findEntitys(param);
                        for (CustomerEntityExt entityExt : entitys) {
                            JSONObject data = entityExt.getData();
                            JSONObject addressObj = data.getJSONObject(CustomerManagementEnum.ADDRESS.getAttr());
                            if (Objects.nonNull(addressObj)) {
                                String province = addressObj.getString(PaasConstant.PROVINCE);
                                String city = addressObj.getString(PaasConstant.CITY);
                                String district = addressObj.getString(PaasConstant.DISTRICT);
                                String address = addressObj.getString(PaasConstant.ADDRESS);
                                String addressStr = province + city + district + address;
                                if (StringUtil.isNotEmpty(addressStr)) {
                                    JSONObject location = addressObj.getJSONObject("location");
                                    if (Objects.nonNull(location)) {
                                        String lat = location.getString("lat");
                                        String lon = location.getString("lon");
                                        if (StringUtil.isEmpty(lat) || StringUtil.isEmpty(lon)) {
                                            try {
                                                JSONObject geo = GaodeGeoHelper.geo(addressStr, "");
                                                if (Objects.nonNull(geo)) {
                                                    String latitude = geo.getString("latitude");
                                                    String longitude = geo.getString("longitude");
                                                    location.put("lat", latitude);
                                                    location.put("lon", longitude);
                                                    addressObj.put("location", location);
                                                    data.put(CustomerManagementEnum.ADDRESS.getAttr(), addressObj);

                                                    entityExt.setData(data);
                                                    customerModel.update(entityExt);
                                                }
                                            } catch (XbbException e) {
                                                continue;
                                            }
                                        }
                                    } else {
                                        try {
                                            JSONObject geo = GaodeGeoHelper.geo(addressStr, "");
                                            if (Objects.nonNull(geo)) {
                                                String latitude = geo.getString("latitude");
                                                String longitude = geo.getString("longitude");
                                                location = new JSONObject();
                                                location.put("lat", latitude);
                                                location.put("lon", longitude);
                                                addressObj.put("location", location);
                                                data.put(CustomerManagementEnum.ADDRESS.getAttr(), addressObj);

                                                entityExt.setData(data);
                                                customerModel.update(entityExt);
                                            }
                                        } catch (XbbException e) {
                                            continue;
                                        }
                                    }
                                }
                            }

                        }
                    }
                }
            } catch (Exception e) {
                LOG.error("fixCustomerCoordinates fail", e);
            }

            response = new XbbResponse<>(new BaseVO());
        }
        return JSON.toJSONString(response);
    }

}
